import {
  createRouter,
  createWebHistory,
  useRouter,
  type RouteRecordRaw,
} from "vue-router";
import { useToken } from "../stores/token";
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: () => import("../views/Layout/index.vue"),
    children: [
      {
        path: "",
        component: () => import("../views/Index/index.vue"),
      },
      {
        path: "/category/:id",
        component: () => import("../views/Category/index.vue"),
      },
      {
        path: "/cart",
        component: () => import("../views/Cart/index.vue"),
        //路由独享守卫
        beforeEnter: () => {
          //执行方法获得 tokenStore 对象
          const tokenStore = useToken();
          //判断用户登录状态
          if (tokenStore.token) {
            //已登录，正常放行
            return true;
          } else {
            //未登录，跳转到登录页面
            const router = useRouter();
            router.push("/login");
          }
        },
      },
    ],
  },
  {
    path: "/login",
    component: () => import("../views/Login/index.vue"),
  },
];
const router = createRouter({
  history: createWebHistory(),
  routes,
});
export default router;
